<template>
	<view class="container" :style="{ paddingTop: safeAreaInsets.top +30+ 'px' }">
		<!-- 头部标题 -->
		<view class="header">
			<text class="title">选择您感兴趣的标签</text>
			<text class="subtitle">我们将为您推荐相关的圈子</text>
		</view>

		<!-- 标签列表 -->
		<view class="tags-container">
			<view class="category-section" v-for="category in categorizedTags" :key="category.name">
				<text class="category-title">{{ category.name }}</text>
				<view class="tags-grid">
					<view v-for="tag in category.tags" :key="tag.id"
						:class="['tag-item', { 'selected': selectedTags.includes(tag.id) }]" @click="toggleTag(tag.id)">
						<text class="tag-text">{{ tag.tagName }}</text>
						<view v-if="selectedTags.includes(tag.id)" class="check-icon">✓</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="footer">
			<view class="selected-count">
				<text>已选择 {{ selectedTags.length }} 个标签</text>
			</view>
			<view class="button-group">
				<button class="skip-btn" @click="skipSelection">跳过</button>
				<button class="confirm-btn" :disabled="isJoining || selectedTags.length === 0"
					@click="confirmSelection">
					{{ isJoining ? '加入中...' : '确认选择' }}
				</button>
			</view>
		</view>

		<!-- 加载提示 -->
		<view v-if="isLoading" class="loading-overlay">
			<view class="loading-content">
				<text class="loading-text">加载中...</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, computed } from 'vue'
	import { getAllTaglist, type TagsInfo } from '@/api/tag/tag'
	import { getCircleByTagId, joinCircle, type CircleBasicInfo } from '@/api/circle/circle'

	// 响应式数据
	const allTags = ref<TagsInfo[]>([])
	const selectedTags = ref<number[]>([])
	const isLoading = ref(false)
	const isJoining = ref(false)

	// 获取屏幕边界到安全区域距离
	const { safeAreaInsets } = uni.getWindowInfo()

	// 计算属性：按分类分组的标签
	const categorizedTags = computed(() => {
		const categories : { [key : string] : TagsInfo[] } = {}

		allTags.value.forEach(tag => {
			const category = tag.tagCategory || '其他'
			if (!categories[category]) {
				categories[category] = []
			}
			categories[category].push(tag)
		})

		return Object.keys(categories).map(name => ({
			name,
			tags: categories[name]
		}))
	})

	// 获取所有标签
	const loadTags = async () => {
		try {
			isLoading.value = true
			const response = await getAllTaglist()
			console.log(response.rows)
			if (response.code === 200) {
				allTags.value = response.rows || response.data || []
			} else {
				uni.showToast({
					title: '获取标签失败',
					icon: 'error'
				})
			}
		} catch (error) {
			console.error('获取标签失败:', error)
			uni.showToast({
				title: '网络错误',
				icon: 'error'
			})
		} finally {
			isLoading.value = false
		}
	}

	// 切换标签选择状态
	const toggleTag = (tagId : number) => {
		const index = selectedTags.value.indexOf(tagId)
		if (index > -1) {
			selectedTags.value.splice(index, 1)
		} else {
			selectedTags.value.push(tagId)
		}
	}

	// 根据标签获取圈子并加入
	const joinCirclesByTags = async (tagIds : number[]) => {
		const joinedCircles : string[] = []
		const failedTags : string[] = []
		const allCircles : CircleBasicInfo[] = [] // 存储所有获取到的圈子
		const circleMap = new Map<number, CircleBasicInfo>() // 用于去重的Map

		// 第一步：获取所有标签对应的圈子
		for (const tagId of tagIds) {
			try {
				// 获取该标签对应的圈子
				const circleResponse = await getCircleByTagId(tagId)
				if (circleResponse.code === 200 && circleResponse.data?.length > 0) {
					const circles : CircleBasicInfo[] = circleResponse.data
					
					// 将圈子添加到Map中进行去重（以圈子ID为key）
					circles.forEach(circle => {
						if (!circleMap.has(circle.id)) {
							circleMap.set(circle.id, circle)
						}
					})
				}
			} catch (error) {
				console.error(`获取标签${tagId}对应圈子失败:`, error)
				const tag = allTags.value.find(t => Number(t.id) === tagId)
				failedTags.push(tag?.tagName || '未知标签')
			}
		}

		// 第二步：将Map转换为数组，得到去重后的圈子列表
		const uniqueCircles = Array.from(circleMap.values())
		
		console.log(`去重前圈子总数: ${allCircles.length}, 去重后圈子数: ${uniqueCircles.length}`)

		// 第三步：加入去重后的圈子
		for (const circle of uniqueCircles) {
			try {
				const joinResponse = await joinCircle(circle.id)
				if (joinResponse.code === 200) {
					joinedCircles.push(circle.circleName || '未知圈子')
					console.log(`成功加入圈子: ${circle.circleName}`)
				} else {
					console.warn(`加入圈子失败: ${circle.circleName}, 原因: ${joinResponse.msg}`)
				}
			} catch (joinError) {
				console.error(`加入圈子失败: ${circle.circleName}`, joinError)
			}
		}

		return { joinedCircles, failedTags }
	}

	// 确认选择
	const confirmSelection = async () => {
		if (selectedTags.value.length === 0) {
			uni.showToast({
				title: '请至少选择一个标签',
				icon: 'none'
			})
			return
		}

		try {
			isJoining.value = true

			uni.showLoading({
				title: '正在加入圈子...'
			})

			const { joinedCircles, failedTags } = await joinCirclesByTags(selectedTags.value)

			uni.hideLoading()

			// 显示结果
			// if (joinedCircles.length > 0) {
			// 	uni.showModal({
			// 		title: '加入成功',
			// 		content: `成功加入 ${joinedCircles.length} 个圈子：${joinedCircles.slice(0, 3).join('、')}${joinedCircles.length > 3 ? '等' : ''}`,
			// 		showCancel: false,
			// 		success: () => {
			// 			navigateToHome()
			// 		}
			// 	})
			// 	navigateToHome()
			// } else {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '未找到相关圈子或加入失败，请稍后重试',
			// 		showCancel: false,
			// 		success: () => {
			// 			navigateToHome()
			// 		}
			// 	})
			// }
			navigateToHome()
		} catch (error) {
			console.error('确认选择失败:', error)
			uni.hideLoading()
			uni.showToast({
				title: '操作失败',
				icon: 'error'
			})
		} finally {
			isJoining.value = false
		}
	}

	// 跳过选择
	const skipSelection = () => {
		uni.showModal({
			title: '确认跳过',
			content: '',
			success: (res) => {
				if (res.confirm) {
					navigateToHome()
				}
			}
		})
	}

	// 导航到首页
	const navigateToHome = () => {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}

	// 页面加载时获取标签
	onMounted(() => {
		loadTags()
	})
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #FFFFFF;
		padding: 40rpx 30rpx 120rpx;
		position: relative;
	}

	.header {
		text-align: center;
		margin-bottom: 60rpx;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: #333333;
			display: block;
			margin-bottom: 20rpx;
		}

		.subtitle {
			font-size: 28rpx;
			color: #666666;
			display: block;
		}
	}

	.tags-container {
		max-height: calc(100vh - 400rpx);
		overflow-y: auto;
	}

	.category-section {
		margin-bottom: 50rpx;

		.category-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333333;
			display: block;
			margin-bottom: 30rpx;
			padding-left: 20rpx;
			border-left: 6rpx solid #667eea;
		}
	}

	.tags-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.tag-item {
		position: relative;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 50rpx;
		padding: 20rpx 30rpx;
		min-width: 120rpx;
		flex-shrink: 0;
		transition: all 0.3s ease;
		border: 2rpx solid transparent;

		&.selected {
			background: #4CAF50;
			border-color: #45a049;
			transform: scale(1.05);

			.tag-text {
				color: #ffffff;
				font-weight: 600;
			}
		}

		&:active {
			transform: scale(0.95);
		}
	}

	.tag-text {
		font-size: 28rpx;
		color: #333333;
		transition: color 0.3s ease;
	}

	.check-icon {
		position: absolute;
		top: -8rpx;
		right: -8rpx;
		width: 32rpx;
		height: 32rpx;
		background: #ffffff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		color: #4CAF50;
		font-weight: bold;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 30rpx;
		border-top: 1rpx solid #e0e0e0;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.selected-count {
		text-align: center;
		margin-bottom: 20rpx;

		text {
			font-size: 28rpx;
			color: #666666;
		}
	}

	.button-group {
		display: flex;
		gap: 20rpx;
	}

	.skip-btn,
	.confirm-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		border: none;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
		}
	}

	.skip-btn {
		background: #f5f5f5;
		color: #666666;

		&:hover {
			background: #e0e0e0;
		}
	}

	.confirm-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #ffffff;
		font-weight: 600;

		&:disabled {
			background: #cccccc;
			color: #999999;
			transform: none;
		}

		&:not(:disabled):hover {
			box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.4);
		}
	}

	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.loading-content {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 60rpx 80rpx;
		text-align: center;
	}

	.loading-text {
		font-size: 32rpx;
		color: #333333;
	}

	/* 滚动条样式 */
	::-webkit-scrollbar {
		width: 8rpx;
	}

	::-webkit-scrollbar-track {
		background: rgba(255, 255, 255, 0.1);
		border-radius: 4rpx;
	}

	::-webkit-scrollbar-thumb {
		background: rgba(255, 255, 255, 0.3);
		border-radius: 4rpx;
	}

	::-webkit-scrollbar-thumb:hover {
		background: rgba(255, 255, 255, 0.5);
	}
</style>